// 菜单tag数据
import { defineStore } from 'pinia'
import { store } from '../index'


export const tagList = defineStore('tag',{
        state:()=>{
            return {
                defaultActive:'/home',  // 这是菜单选中页
                tagData:[{
                    name:'首页', // 名字
                    path:'/home', // 路径
                    isCurrent:true, // 是否为默认菜单
                }],
            }
        },
        getters: {
            getTagData: (state) => state.tagData
        },
        actions : {
            // 添加
            pushTagData:(state,value) =>  {
                let tagList = state.getTagData;
                let isPush = false;
                // 将所有菜单的默认设置为false
                tagList.forEach((item)=>{
                    item.isCurrent = false
                });
                for (let i=0;i<tagList.length;i++) {
                    if (value.path === tagList[i].path) {
                        tagList[i].isCurrent = true; // 相同菜单点击
                        state.defaultActive = tagList[i].path;
                        isPush = false;
                        break;
                    }else{
                        state.defaultActive = value.path;
                        isPush = true;
                    }
                }
                if(isPush){
                    state.tagData.push(value)
                }
            },
            // 删除
            delTagData:(state,value)=>{
                let path = '';
                let tagList = state.getTagData;
                if(tagList.length === 1){
                    path = tagList[0].path;
                    state.defaultActive = tagList[0].path;
                    return path
                }
                tagList.forEach((item,i)=>{
                    if(item.path === value.path){
                        if(value.isCurrent){
                            path = tagList[i-1].path;
                            state.defaultActive = tagList[i-1].path;
                            tagList[i-1].isCurrent = true;
                        }
                        tagList.splice(i,1);
                    }
                });

                return path


            },

        },
        // 开启数据缓存
        persist: {
            enabled: true,
            strategies: [
                {
                    key: 'tagInfo', //设置存储的key
                    storage: sessionStorage, //表示存储在sessionStorage
                }
            ]
        }
    },
);



// tagStoreHook
export function tagStoreHook() {
    return tagList(store)
}
